
#include <BImage>
#include <BScene>
#include <BMaterial>

#include "ReadWrite_stl.h"

ReadWrite_stl::ReadWrite_stl()
{
	_author = "zym";
	_version = "1.0";
	_description = "This is BWE Plugin for reading *.jpg image file, write width libjpeg, thank a lot !";
}
ReadWrite_stl::~ReadWrite_stl()
{

}

struct FaceInfo
{
	BVector normal;
	BVector v0;
	BVector v1;
	BVector v2;
	short def;
};
bool ReadWrite_stl::readObject(const BString& fileName, BObject* object)
{
	BScene* scene = dynamic_cast<BScene*>(object);
	BNode* node = dynamic_cast<BNode*>(object);
	BMesh* mesh = dynamic_cast<BMesh*>(object);
	if (!scene && !node && !mesh)
		return false;

	_mates.clear();
	if(!_file.open(fileName, BFile::Mode_Read))
		return 0;
	
	char name[80];
	int size = 0;
	_file.read(name, 80);
	_file.read(&size, 4);

	if (!mesh)
		mesh = new BMesh();

	FaceInfo info;
	BVectorArray* vertices = new BVectorArray(size * 3);
	BVectorArray* normals = new BVectorArray(size * 3);

	for (int i = 0; i < size; i++)
	{
		_file.read(&info, 50);
		int pos = i * 3;
		(*vertices)[pos + 0] = info.v0;
		(*vertices)[pos + 1] = info.v1;
		(*vertices)[pos + 2] = info.v2;
		(*normals)[pos] = info.normal;
		(*normals)[pos + 1] = info.normal;
		(*normals)[pos + 2] = info.normal;
	}

	BMaterial* material = new BMaterial();

	mesh->setVertices(vertices);
	mesh->setNormals(normals);
	mesh->setMaterial(material);

	if (scene)
		scene->inserts(mesh);

	if (node)
		node->addShape(mesh);

	_file.close();
	return true;
}
bool ReadWrite_stl::writeObject(const BString& fileName, const BObject* object)
{
	return false;
}

const BString& ReadWrite_stl::author() const
{
	return _author;
}
const BString& ReadWrite_stl::version() const
{
	return _version;
}
const BString& ReadWrite_stl::description() const
{
	return _description;
}
const BString& ReadWrite_stl::log() const
{
	return _log;
}


MateStl* ReadWrite_stl::findMaterial(const BString& matName)
{
	for (BList<MateStlHolder>::iterator it = _mates.begin(); it != _mates.end(); ++it)
	{
		MateStl* mate = it->ptr();
		BMaterial* material = mate->material.ptr();
		if(material->name() == matName)
			return mate;
	}
	return 0;
}

